<?php
//return lottery_json();exit;
lottery_json();exit;
session_start();
require_once("../includes/public.inc.php");
$username = isset($_SESSION['username'])?$_SESSION['username']:'';
$gift = mysql_fetch_array(mysql_query("select * from ".DBQIAN."gift where id=3 order by id desc limit 1"));
$user = mysql_fetch_array(mysql_query("select * from ".DBQIAN."users where username='".$username."' order by id desc limit 1"));
if (!empty($_GET['app']) && $_GET['app'] == 'lottery_json') 
{
	if ($user['credit']<$gift['credit'])
	{
		echo '积分不足';
	}
	else 
	{
		$rid = lottery_json();//就是为了获取奖项
	//	echo $rid;exit;
		if ($rid == 0)//不中奖
		{
			$in_exchange = mysql_query("insert into ".DBQIAN."exchange (credit,time,username,giftname,qty,post_id,usercredit,nowcredit,status,type) values(".$gift['credit'].",'".date('Y-m-d H:i:s',time())."','".$username."','no get praise',1,1,".$user['credit'].",".($user['credit']-$gift['credit']).",0,3)");
			$up_user = mysql_query("update ".DBQIAN."users set credit=".($user['credit']-$gift['credit'])." where username='".$username."'");
			return $rid;
		}
		else//中奖
		{
			$praise = mysql_fetch_array(mysql_query("select * from ".DBQIAN."ticket where id=".$rid." order by id desc limit 1"));
			$in_exchange = mysql_query("insert into ".DBQIAN."exchange (credit,time,username,giftname,qty,post_id,usercredit,nowcredit,status,type) values(".$gift['credit'].",'".date('Y-m-d H:i:s',time())."','".$username."','".$praise['praisecontent']."',1,1,".$user['credit'].",".($user['credit']-$gift['credit']).",0,3)");
			$up_user = mysql_query("update ".DBQIAN."users set credit=".($user['credit']-$gift['credit'])." where username='".$username."'");
			return $rid;
		}
	}
}

function ar()
{
	session_start();
	require_once("../includes/public.inc.php");
	$username = isset($_SESSION['username'])?$_SESSION['username']:'';
	$record = array();
	$dh = mysql_query("select * from ".DBQIAN."exchange where username='".$username."' and giftname not like 'no get praise'");
	while($row = mysql_fetch_assoc($dh)){
		$record[] = $row['giftname'];
	}
	print_r($record);
}

/**
 * 中奖机率计算
 */
function lottery_json() {
	session_start();
	require_once("../includes/public.inc.php");
	$username = isset($_SESSION['username'])?$_SESSION['username']:'';
	$record = array();
	$dh = mysql_query("select * from ".DBQIAN."ticket");
	while($row = mysql_fetch_assoc($dh)){
		$record[] = $row['praisenumber'];
	}
	//print_r($record);exit;
	//数据配置
    //奖品概率
    $proArr = array(
        '1' => 20, //'一等奖'
        '2' => 20, //'二等奖'
        '3' => 20, //'三等奖'
        '4' => 20, //'四等奖'
        '5' => 20, //'五等奖'
        '6' => 20, //'六等奖'
        '7' => 50,
        '8' => 50,
        '9' => 50,
        '10' => 50
    );
    //奖品库存
    //$proCount = $record;
    $proCount = array(
        '1' => $record[0],
        '2' => $record[1],
        '3' => $record[2],
        '4' => $record[3],
        '5' => $record[4],
        '6' => $record[5],
        '7' => $record[6],
        '8' => $record[7],
        '9' => $record[8],
        '10' => $record[9]
    );
    $file = 'num.txt';
    $data = array(
        '1' => 0, '2' => 0, '3' => 0, '4' => 0, '5' => 0, '6' => 0
    );
    if (!file_exists($file)) 
    {
        file_put_contents($file, serialize($data));
    } 
    else 
    {
        $str = file_get_contents($file);
        $data = unserialize($str);//反序列化，把字符转化为数组，然后使用计算一共有多少奖品被抽取
    }
    //上面试准备数据，其实概率和库存使用相互的
    $rid = getRand($proArr, $proCount);//计算中奖的概率
    if ($rid > 6) 
    {
        $rid = 0;
    } 
    else 
    {
        $rid = returnRid($rid, $file, $data, $proCount, $proArr);
    }
    echo $rid;//这是最开始的返回数据
	return $rid;
}

function returnRid($rid, $file, $data, $proCount, $proArr) {
    $data[$rid] = $data[$rid] + 1;    
    $count = $proCount[$rid]; // 总库存
    if ($count < $data[$rid])
    {
        // 如果抽取的数据大于总库存时库存清0
        $proCount[$rid] = 0;
        // 然后继续计算一直计算出某个值的库存不为0
        $rid = returnRid($rid, $file, $data, $proCount, $proArr);//
    }
    else
    {
        // 写入缓存
        file_put_contents($file, serialize($data));
    }
    return $rid;
}

/**
 * 中奖概率计算, 能用
 * $proArr = array('1'=>'概率', '2'=>'概率');
 * $proCount = array('1'=>'库存', '2'=>'库存');
 */
function getRand($proArr, $proCount) {
    $result = '';
    $proSum = 0;
    foreach ($proCount as $key => $val) {
        if ($val <= 0) 
        {
            continue;
        } 
        else 
        {
            $proSum = $proSum + $proArr[$key];
        }
    }
    foreach ($proArr as $key => $proCur) {
        if ($proCount[$key] <= 0) 
        {
            continue;
        } 
        else 
        {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) 
            {
                $result = $key;
                break;
            } 
            else 
            {
                $proSum -= $proCur;
            }
        }
    }
    unset($proArr);
    return $result;
}
